<template>
  <!-- 一对一关系 -->
  <div v-if="properties.relationType == 1 && subTableFalg()">
    <div class="area-header" style="margin-bottom: 0;">
      <span class="area-header-title">{{ properties.describe }}</span>
    </div>
    <el-row style="display: flex;flex-wrap: wrap">
      <template>
        <el-col
          v-for="(item, index) in properties.properties"
          :key="'col' + index"
          :span="parseInt(item.fieldGrid)"
        >
          <!-- :dict-options="item.dict" -->
          <online-query-form-item
            v-if="subPojoFalg(item)"
            :ref="item.field"
            :key="'form' + item.field"
            :item="item"
            :code="code"
            :query-param="getAddResult(pojo[item.key])"
            :verify="getVerify(item)"
            :properties="properties"
            :is-button="isButton"
            :is-add="isAdd"
            @take="searchSelectOptionDataOneToOne"
          />
        </el-col>
      </template>
    </el-row>
  </div>
  <!-- 一对多关系 -->
  <div v-else-if="properties.relationType == 2 && subTableFalg()">
    <div class="area-header">
      <span class="area-header-title">{{ properties.describe }}</span>
    </div>
    <template>
      <el-table
        ref="multipleTable"
        :data="pojo[properties.key]"
        style="width: 100%"
        border
        max-height="400px"
        :cell-style="{ padding: '3px' }"
        :row-style="{ height: '0' }"
      >
        <template>
          <!-- <template v-for="(item, index) in pojo[properties.key][0]"> -->
          <template>
            <el-table-column
              v-for="(item, index) in properties.columns"
              :key="'column' + index"
              :prop="item.key"
              :label="item.title"
              :min-width="item.width"
              align="center"
            >
              <template slot="header" slot-scope="{}">
                <i v-show="getVerify(item).length>0" style="color: #ff4949; margin-right: 4px">*</i>
                <span>{{ item.title }}</span>
              </template>
              <template slot-scope="scope">
                <!-- :dict-options="scope.row[index].dict" -->
                <online-query-form-item
                  :ref="`${scope.$index}${scope.row[index].field}`"
                  :key="'scope' + scope.row.$index"
                  :item="scope.row[index]"
                  :cache-temp-pojo="formPojo"
                  :code="code"
                  :query-param="scope.row[index]"
                  :row-index="scope.$index+'.'+index"
                  :properties="properties"
                  :verify="getVerify(item)"
                  :is-button="isButton"
                  :is-add="isAdd"
                  @take="searchSelectOptionData"
                />
              </template>
            </el-table-column>
          </template>
          <el-table-column
            :label="$t('操作')"
            align="center"
            class-name="small-padding fixed-width"
            :width="properties.columns.length==0?'':'180'"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                v-if="isButton"
                size="small"
                type="text"
                icon="el-icon-delete"
                @click="delField(scope.$index)"
              >{{ $t("删除") }}</el-button>
              <!-- 子表显示的按钮 -->
              <OnlineBtnList
                :row-data="pojo[properties.key][scope.$index]"
                :row-index="scope.$index"
                :btn-model-list="properties.btnList"
                @receve="receveData"
              />
            </template>
          </el-table-column>
        </template>
      </el-table>
      <div v-if="properties.columns.length!=0 && isButton" class="tol">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="addField"
        >{{ $t("添加") }}</el-button>
      </div>
    </template>
  </div>

</template>

<script>
import OnlineQueryFormItem from '@/components/desform/online/OnlineQueryFormItem.vue'
import { requestMethod } from '@/api/system/desform/onlineForm/onlCgformHead'
import { getRules } from '@/views/system/desform/release/formDataProperty.js'
import { judge, watchPropComputed, watchMasterPropComputed, masterJudge } from './onlineUtils.js'
import OnlineBtnList from '@/components/desform/online/onlineBtnList.vue'

export default {
    name: 'OnlineSubForm',
    components: {
        OnlineQueryFormItem,
        OnlineBtnList
    },
    props: {
      dictOptions: {
        type: Array,
        default: () => {},
        required: false
      },
      properties: {
        type: Object,
        default: () => {},
        required: false
      },
      //  模式 table(表格) form (表单)
      pattern: {
        type: String,
        default: () => '',
        required: false
      },
      code: {
        type: String,
        default: () => '',
        required: false
      },
      // 为了校验加上了这个属性。。。
      formPojo: {
        type: Object,
        default: () => {},
        required: false
      },
      // 按钮是否展示
      isButton: {
        type: Boolean,
        default: () => true,
        required: false
      },
      // 新增带出数据
      addResult: {
        type: Object,
        default: () => {},
        required: false
      },
      // 是否新增
      isAdd: {
        type: Boolean,
        default: () => true,
        required: false
      }
    },
    data() {
      return {
        // 三种模式 模糊查询 single 范围查询 group 精确查询 accurate
        mode: 'single',
        btnDis: true,
        // 下拉框选项
        options: [],
        pojo: this.formPojo,
        tableData: [],
         // 表格选中项
        multipleTable: [],
        rowIndex: 0
      }
    },
    computed: {
        pojoProp() {
          return watchPropComputed(this.pojo, this.properties)
        },
        subPojoProp() {
          return watchMasterPropComputed(this.pojo, this.properties.properties)
        }
    },
    watch: {
        pojoProp: {
          handler() {
              this.subTableFalg()
          },
          deep: true,
          immediate: true
      },
      formPojo: {
        handler() {
          watchPropComputed(this.pojo, this.properties)
          // this.subTableFalg()
            if (this.properties.properties) {
                this.properties.properties.forEach(e => {
                    this.subPojoFalg(e)
                })
            }
        },
        deep: true,
        immediate: true
      }
    },
    created() {
    },
    methods: {
      subTableFalg() {
        return judge(this.properties)
      },
      subPojoFalg(item) {
        return masterJudge(item, this.pojo)
      },
    addField() {
         // 不是数组置为空数组
        if (!(this.pojo[this.properties.key] instanceof Array)) {
           this.$set(this.pojo, this.properties.key, [])
         }
        var rowObj = JSON.parse(JSON.stringify(this.properties.columns))
         rowObj.map(e => { // 赋默认值
            e[e.field] = e.delVal
         })
        this.pojo[this.properties.key].push(rowObj)
    },
    // 删除字段
    delField(index) {
       this.pojo[this.properties.key].splice(index, 1)
    },
    getVerify(item) {
        return getRules(item)
      },
    receveData(data, currentBtnItem, index) {
        // 这里得获取关联的表名
        this.$set(this.pojo[this.properties.key][index], currentBtnItem?.tbName, Object.assign({}, data))
    },
    // 查询 关联数据下拉框
    searchSelectOptionData(val, cascaderProp, rowIndex, stopClear) {
        // console.log('onlineSubForm change事件触发', val, cascaderProp, rowIndex, stopClear)
         if (!cascaderProp.cascader_f) { // 最后一级不需要处理
          return
        }
         const crruntIndex = rowIndex.toString().split('.')[0] + cascaderProp.cascader_f
        // 清空所有下级的数据
        this.properties.columns.map(dom => {
            if (dom.cascaderProp) { // 是联动组件
                const eleProp = dom.cascaderProp
                const deep = cascaderProp.deep // 当前联动的层级深度 1为最大
                if (eleProp.deep > deep) {
                  // 需要清空
                  if ((this.$refs[crruntIndex] instanceof Array)) {
                       this.$refs[crruntIndex][0].cascadeOptions = []
                  }
                  this.pojo[this.properties.key].map((i_element, index) => {
                    i_element.map(element => {
                    if (element.cascaderProp && element.cascaderProp.deep > deep) {
                          if (!stopClear) {
                                  if (rowIndex.toString().split('.')[0] === index.toString()) {
                                       element[element.field] = undefined
                                  }
                            }
                          }
                   })
                  })
                }
                 this.$forceUpdate()
            }
        })
         const target = this.properties.columns.filter(item => item.field === cascaderProp.cascader_f)
          if (!target) {
              this.msgError('配置错误！')
              return
          }
          const dto = {
              'dealId': this.$route.query.id,
              'fundId': this.$route.query.id,
              'lpId': this.$route.query.lpId,
              'companyId': this.$route.query.companyId,
              'key': val,
              'model': target[0].cascaderProp
         }
         requestMethod(`/head/OnlineApiTest/api/findSelectOption`, 'post', dto).then(response => {
            // 赋值下一级的数据 如果是一对多的情况怎么办
             this.$refs[crruntIndex][0].cascadeOptions = response.data
         })
      },
       searchSelectOptionDataOneToOne(val, cascaderProp) {
        if (!cascaderProp || !cascaderProp.cascader_f) { // 最后一级不需要处理
            return
        }
        // 清空所有下级的数据
        this.properties.properties.map(dom => {
            if (dom.cascaderProp) { // 是联动组件
                const eleProp = dom.cascaderProp
                const deep = cascaderProp.deep // 当前联动的层级深度 1为最大
                if (eleProp.deep > deep) {
                  // 需要清空

                  if (this.$refs[dom.field]) {
                    this.$refs[dom.field][0].cascadeOptions = []
                    this.pojo[dom.key][dom.field] = undefined
                      // if (!this.isAdd) {
                      //     this.pojo[dom.key][dom.field] = undefined
                      // }
                  }
                }
                 this.$forceUpdate()
            }
        })
         // 找到对应下级的组件
          const target = this.properties.properties.filter(item => item.field === cascaderProp.cascader_f)
          if (!target) {
              this.msgError('配置错误！')
              return
          }
         const dto = {
              'dealId': this.$route.query.id,
              'fundId': this.$route.query.id,
              'lpId': this.$route.query.lpId,
              'companyId': this.$route.query.companyId,
              'key': val,
              'model': target[0].cascaderProp
         }

         requestMethod(`/head/OnlineApiTest/api/findSelectOption`, 'post', dto).then(response => {
            this.$refs[cascaderProp.cascader_f][0].cascadeOptions = response.data
         })
    },
      firstLoadDataOption(initArr, value, cascaderProp) { // 第一次加载页面需要调用的关联数据
        if (!cascaderProp) {
          return
        }
        if (value) { // 如果有值才调用关联数据
          const target = initArr.filter(item => item.field === cascaderProp.cascader_f)
          if (!target || !target[0]) {
            return
          }
          const dto = {
            'dealId': this.$route.query.id,
            'fundId': this.$route.query.id,
            'lpId': this.$route.query.lpId,
            'companyId': this.$route.query.companyId,
            'key': value,
            'model': target[0].cascaderProp
          }
          requestMethod(`/head/OnlineApiTest/api/findSelectOption`, 'post', dto).then(response => {
            // TODO 这里需要更改
            if (this.$refs[cascaderProp.cascader_f]) {
              this.$refs[cascaderProp.cascader_f][0].cascadeOptions = response.data
            } else {
              this.$refs[target[0].key][0].$refs[target[0].field][0].cascadeOptions = response.data
            }
          })
        }
      },
      // 获取新增带出数据
      getAddResult(pojo) {
        if (this.addResult) {
          // 一对一字段解析
          var arr = []
          if (this.properties && this.properties.properties && this.properties.properties.length > 0) {
            Object.keys(this.properties.properties).map(key => {
              arr = arr.concat(this.properties.properties[key])
            })
          }
          Object.keys(this.addResult).map((key) => {
            if (arr) {
              arr.forEach(item => {
                if (item.field === key && item.cascaderProp && item.view === 'cascader_component') {
                  // 若是联动组件需要调用关联数
                  this.firstLoadDataOption(arr, this.addResult[key], item.cascaderProp)
                }
              })
            }
           pojo[key] = this.addResult[key]
          })
        }
        return pojo
      }
    }
  }
</script>

<style scoped>
.buttons {
  margin-bottom: 10px;
}
.cell {
  height: 54px !important;
}
.el-form-item {
    /* margin-bottom: 22px; */
    margin: 12px 0 !important;
}
.dataForm .el-row .el-form-item {
    min-height: 54px;
}
</style>
